const router = require('koa-router')()
const Mock = require('mockjs')
const { query } = require('../db')
const jwt = require('jsonwebtoken')

const auth = require('../middlewares/auth')
const err = require('../middlewares/err')

// 创建数据
router.get('/api/addMysqlList',err(), async (ctx, next) => {
  // 创建数据
  const data = Mock.mock({
    "list|400-1000": [
      {
        idCard: "@id",
        name: "@cname",
        "sex|1": ['男', '女'],
        address: "@city",
        "relation|1": ["户主", "配偶", "子女"],
        birthday: "@date"
      }
    ]
  })

  // 将创建号的数据  添加到数据库
  data.list.forEach(async item => {
    // 添加数据库
    await query(`insert into list values ("${item.name}", null, "${item.sex}", "${item.address}", "${item.relation}", "${item.birthday}", "${item.idCard}")`)
  })

  ctx.body = {
    code: 1,
    msg: '添加成功'
  }
})

// 登录
router.post('/api/login',err(), async (ctx, next) => {
  // 获取前端传来的参数
  const { username, password } = ctx.request.body;

  // 搜索数据库  select:返回数组
  const data = await query(`select * from userlist where username="${username}" and password="${password}"`)

  if (data.length) {
    // 在数据库中能找到数据
    ctx.body = {
      code: 1,
      token: jwt.sign(data[0].id, '1908A')
    }
  } else {
    ctx.status = 401;
    // 找不到
    ctx.body = {
      code: 0,
      msg: '用户名和密码错误'
    }
  }
})


router.get('/api/getUserInfo',err(),  async (ctx) => {
  // 获取请求头中的token
  const { authorization } = ctx.request.headers;

  try {
    const id = jwt.verify(authorization, '1908A')

    const data = await query(`select * from userlist where id=${id}`)

    ctx.body = {
      code: 1,
      data: data[0]
    }
  } catch (error) {
    ctx.body = {
      code: 0,
      msg: '登录已过期 请重新登录'
    }
  }

})

// 获取列表
router.post('/api/getList',err(), auth(), async (ctx) => {
  const { current, size, name = "", sex = "", address = "" } = ctx.request.body;

  // 获取list
  const data = await query(`select * from list where name like "%${name}%" and sex like "%${sex}%" and address like "%${address}%" ORDER BY id DESC limit ${(current - 1) * size}, ${size}`)

  const total = await query(`SELECT count(*) AS count FROM list where name like "%${name}%" and sex like "%${sex}%" and address like "%${address}%"`)

  ctx.body = {
    code: 1,
    data: data,
    // 总条数
    total: total[0].count
  }
})

// 删除
router.delete('/api/deletaItem/:id',err(), auth(), async (ctx) => {

  await query(`delete from list where id=${ctx.params.id}`)

  ctx.body = {
    code: 1
  }
})

// 添加 / 修改
router.post('/api/addItemOrEditItem',err(), auth(), async (ctx) => {
  // 获取前端传来的参数
  const { name, sex, address, idCard, relation, birthday, id } = ctx.request.body;

  if (id) {
    // 如果id存在 就说明史修改
    await query(`update list set name="${name}", sex="${sex}", address="${address}", idCard="${idCard}", relation="${relation}", birthday="${birthday}" where id=${id} `)
  } else {
    // 添加
    // 添加mysql
    await query(`insert into list values ("${name}", null, "${sex}", "${address}", "${relation}", "${birthday}", "${idCard}")`)
  }

  ctx.body = {
    code: 1,
    msg: id ? "修改成功" : '添加成功'
  }
})

router.post('/api/getDetail',err(), auth(), async (ctx) => {
  // 获取前端传来的参数
  const { id } = ctx.request.body;

  const data = await query(`select * from list where id=${id * 1}`)

  ctx.body = {
    code: 1,
    data: data[0]
  }
})

module.exports = router
